package com.ato.Thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangjing
 * @create 2021--09--19--15:01
 * <p>
 * 解决线程同步安全的方式3： 用的多的
 */
public class LockTest {
    public static void main(String[] args) {
        Window w1 = new Window();
        Thread t1 = new Thread(w1);
        Thread t2 = new Thread(w1);
        Thread t3 = new Thread(w1);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口1");
        t1.start();
        t2.start();
        t3.start();
    }
}

class Window implements Runnable {
    private int tick = 100;
    //    1：实例化lock
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {

            try {
//               锁住线程
                lock.lock();
                if (tick > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":售票，票号为" + tick);
                    tick--;
                } else {
                    break;
                }
            } finally {
//          释放线程
                lock.unlock();
            }

        }
    }
}

